<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport" v-if="permission.glueCodeManage_import">导入胶水条码</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete" v-if="permission.glueCodeManage_delete">删 除 </el-button>
      </template>
    </avue-crud>
    <el-dialog title="胶水条码导入" append-to-body :visible.sync="excelBox" v-if="excelBox" width="555px">
      <avue-form ref="excelFile" :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate" class="el-icon-download el-icon--right">模板下载</el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, importGlueByExcel, removePack } from '@/api/equipment-manage/glue-manage.js';
import { getToken } from '@/util/auth';
import { mapGetters } from 'vuex';
import { exprot } from '@/api/repair/failureconfig';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'GULE_CODE_MANAGE',
      fileList: [],
      form: {},
      excelForm: {},
      defaults: {},
      query: {},
      excelBox: false,
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/mes-admin/part/indirect/import-glue'
          },
          {
            label: '数据覆盖',
            prop: 'isCovered',
            type: 'switch',
            align: 'center',
            width: 80,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择是否覆盖',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      },
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        menu: false,
        selection: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        searchSpan: 5,
        menuWidth: 200, //弹框内字段宽度属性
        //   dialogWidth: 880, //弹框宽度属性
        labelWidth: '180',
        //   searchMenuSpan: 7,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '胶水条码',
            prop: 'barCode',
            search: true,
            searchOrder: 2
          },
          {
            label: '胶水批次',
            prop: 'lotNo',
            search: true
          },
          {
            label: '生产日期',
            prop: 'productionDate'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '正常',
                value: 1
              },
              {
                label: '解冻中',
                value: 2
              },
              {
                label: '解冻完成',
                value: 3
              },
              {
                label: '领用中',
                value: 6
              },
              {
                label: '已报废',
                value: 0
              },
              {
                label: '已解绑',
                value: 8
              },
              {
                label: '已过期',
                value: 9
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'code',
            search: true,
            searchOrder: 1
          },
          {
            label: '保质期天数(天)',
            prop: 'expirationDays'
          },
          {
            label: '保质期到日期',
            prop: 'expirationExpire'
          },
          {
            label: '最短解冻时间(时)',
            prop: 'timeMinRise'
          },
          {
            label: '最长使用时间',
            prop: 'maxUsageTime'
          },
          {
            label: '解冻完成时间',
            prop: 'finishedTime'
          },
          {
            label: '失效时间',
            prop: 'invalidTime'
          }
        ]
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    uploadAfter(res, done, loading, column) {
      done();
      if (res && res.data.code == 400) {
      } else {
        this.excelBox = false;
        this.refreshChange();
      }
      this.$refs.excelFile.resetFields();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePack(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    handleImport() {
      this.excelBox = true;
      this.excelForm.isCovered = 0;
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      params.type = 'GLUE_BARCODE';
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = this._map(data.records, (item, index) => {
          return {
            ...item,
            expirationExpire: this.$moment(item.productionDate).add(item.expirationDays, 'days').format('YYYY-MM-DD HH:mm:ss')
          };
        });
        // this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {},
    rowUpdate(row) {},
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePack([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    async handleTemplate() {
      const data = {
        originalName: '胶水条码数据模板.xlsx',
        attachType: 'EXCEL'
      };
      const res = await exprot({ data });
      const blob = new Blob([res.data]);
      const fileName = '胶水条码数据模板.xlsx';
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },

    uploadFile(params) {
      const file = params.file;
      let fileParams = new FormData();
      fileParams.append('file', file);
      importGlueByExcel(fileParams).then(
        (res) => {
          this.$message({
            type: 'success',
            message: '导入成功!'
          });
          this.fileList = [];
          this.onLoad(this.page, this.query);
        },
        (error) => {
          this.fileList = [];
          this.onLoad(this.page, this.query);
          console.log(error);
        }
      );
    }
  },
  watch: {
    'excelForm.isCovered'() {
      if (this.excelForm.isCovered !== '') {
        const column = this.findObject(this.excelOption.column, 'excelFile');
        column.action = `/api/mes-admin/part/indirect/import-glue?isCovered=${this.excelForm.isCovered ? this.excelForm.isCovered : 0}`;
      }
    }
  }
};
</script>
